package com.yixun.qfbao.api.service.impl;

import com.yixun.common.page.Page;
import com.yixun.qfbao.api.service.ChannelReportService;
import com.yixun.qfbao.api.service.DataCenterService;
import com.yixun.qfbao.api.service.DeptPermissionService;
import com.yixun.qfbao.api.service.PremisesPermissionService;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.common.model.PageDTO;
import com.yixun.qfbao.dao.ChannelReportDao;
import com.yixun.qfbao.dao.DepartmentDao;
import com.yixun.qfbao.model.*;
import com.yixun.qfbao.model.dto.DepartmentDto;
import com.yixun.qfbao.model.dto.PartnerInfoDto;
import com.yixun.qfbao.model.enums.DPDescEnum;
import com.yixun.qfbao.service.CompanyRelationService;
import com.yixun.qfbao.service.PartnerInfoService;
import com.yixun.qfbao.util.DateStyle;
import com.yixun.qfbao.util.DateUtils;
import com.yixun.qfbao.xf.model.CaseMember;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.CaseMemberDto;
import com.yixun.qfbao.xf.model.dto.PremisesDto;
import com.yixun.qfbao.xf.model.enums.DeptPermissionEnum;
import com.yixun.qfbao.xf.service.CaseMemberService;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ChannelReportServiceImpl implements ChannelReportService {

    @Autowired
    ChannelReportDao channelReportDao;
    @Autowired
    DepartmentDao departmentDao;
    @Autowired
    DataCenterService dataCenterService;
    @Autowired
    CompanyRelationService companyRelationService;
    @Autowired
    PartnerInfoService partnerInfoService;
    @Autowired
    DeptPermissionService deptPermissionService;
    @Autowired
    PremisesPermissionService premisesPermissionService;

    @Autowired
    private PremisesService premisesService;
    @Autowired
    private CaseMemberService caseMemberService;

    @Override
    public ChannelCooOrgReportResDto getChannelCooOrgReport(ChannelCooOrgReportReqDto reqDto, PageDTO pageDTO) throws ParseException {
        ChannelCooOrgReportResDto resDto = new ChannelCooOrgReportResDto();
        ChannelReportParam param = new ChannelReportParam();
        param.setPremisesId(reqDto.getPremisesId());
        if(StringUtils.isNotEmpty(reqDto.getBeginDate())){
            param.setBeginDate(DateUtils.stringToDate(reqDto.getBeginDate(), DateStyle.YYYY_MM_DD.getValue()));
        }
        if(StringUtils.isNotEmpty(reqDto.getEndDate())){
            Date endDate = DateUtils.StringToDate(reqDto.getEndDate(), DateStyle.YYYY_MM_DD);
            endDate = DateUtils.addDay(endDate, 1);
            param.setEndDate(endDate);
        }
        param.setLayer(reqDto.getLayer());

        // 未指定分销公司,获取用户所在渠道的所有分销公司
        List<Long> agentCompanies = new ArrayList<>();
        agentCompanies.add(reqDto.getAgentCompany());
        if(Objects.isNull(reqDto.getAgentCompany())){
            PartnerInfo channelPi = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
            agentCompanies = partnerInfoService.listGroupCompanyIdByCompanyId(channelPi.getHigherid(), false);
        }
        if(CollectionUtils.isEmpty(agentCompanies)){
            return resDto;
        }
        param.setAgentCompanies(agentCompanies);

        // 楼盘权限
        List<Long> premisesIds = premisesPermissionService.getPartnerPremisesPermission(Long.valueOf(reqDto.getUserId()));
        if(CollectionUtils.isEmpty(premisesIds)){
            param.setPremisesIds(Arrays.asList(-1L));
        }else{
            param.setPremisesIds(premisesIds);
        }

        // 添加个人权限
        List<Long> agencyDeptIds = deptPermissionService.getPartnerDeptPermission(Long.valueOf(reqDto.getUserId()));
        param.setAgencyDeptIds(agencyDeptIds);
        param.setDeptId(reqDto.getDeptId());
        if(reqDto.getMergeDept()){
            if(Objects.nonNull(reqDto.getDeptId())){
                param.setDeptId(null);
                Department dept = departmentDao.selectById(reqDto.getDeptId());
                DepartmentDto deptDto = new DepartmentDto();
                deptDto.setPermissionCode(dept.getPermissionCode());
                List<Department> deptList = departmentDao.selectListByDto(deptDto);
                if(CollectionUtils.isNotEmpty(deptList)){
                    List<Long> deptIds = deptList.stream().map(Department::getId).collect(Collectors.toList());
                    param.setDeptIds(deptIds);
                }
            }
        }

        int count;
        List<ChannelCooOrgReport> rows = channelReportDao.getChannelCooOrgReportList(param, (pageDTO.getPageNum() - 1) * pageDTO.getPageSize(), pageDTO.getPageSize());

        if(reqDto.getMergeDept()){
            // 合并子部门的所有数据
            // 1、先获取到全量的数据
            // 2、对展示的数据进行计算
            pageDTO.setPageNum(PageDTO.DEFAULT_PAGENUM);
            pageDTO.setPageSize(PageDTO.MAX_PAGESIZE);
            List<ChannelCooOrgReport> allRows = channelReportDao.getChannelCooOrgReportList(param, (pageDTO.getPageNum() - 1) * pageDTO.getPageSize(), pageDTO.getPageSize());
            count = allRows.size();
            rows = mergeChannelCooOrgReport(rows, allRows);
        }else{
            count = channelReportDao.getChannelCooOrgReportCount(param);
        }
        Page<ChannelCooOrgReport> page = new Page<>(count, rows);
        page.setPageSize(pageDTO.getPageSize());
        page.setPageNumber(pageDTO.getPageNum());
        resDto.setPageModel(page);
        return resDto;
    }

    // 合并记录
    List<ChannelCooOrgReport> mergeChannelCooOrgReport(List<ChannelCooOrgReport> rows, List<ChannelCooOrgReport> allRows){
        for (ChannelCooOrgReport ccor: rows){
            Long countOne = ccor.getCountOne();
            Long countTwo = ccor.getCountTwo();
            Long countThree = ccor.getCountThree();
            Long countFour = ccor.getCountFour();
            Long countFive = ccor.getCountFive();
            Long countSix = ccor.getCountSix();
            Long countSeven = ccor.getCountSeven();
            Long countEight = ccor.getCountEight();
            Long countNine = ccor.getCountNine();
            BigDecimal dealAmount = new BigDecimal(StringUtils.defaultIfBlank(ccor.getDealAmount(), "0"));
            for (ChannelCooOrgReport allCcor: allRows){
                if(!ccor.getPermissionCode().equals(allCcor.getPermissionCode())
                && allCcor.getPermissionCode().startsWith(ccor.getPermissionCode())){
                    countOne += allCcor.getCountOne();
                    countTwo += allCcor.getCountTwo();
                    countThree += allCcor.getCountThree();
                    countFour += allCcor.getCountFour();
                    countFive += allCcor.getCountFive();
                    countSix += allCcor.getCountSix();
                    countSeven += allCcor.getCountSeven();
                    countEight += allCcor.getCountEight();
                    countNine += allCcor.getCountNine();
                    dealAmount.add(new BigDecimal(StringUtils.defaultIfBlank(allCcor.getDealAmount(), "0")));
                }
            }
            ccor.setCountOne(countOne);
            ccor.setCountTwo(countTwo);
            ccor.setCountThree(countThree);
            ccor.setCountFour(countFour);
            ccor.setCountFive(countFive);
            ccor.setCountSix(countSix);
            ccor.setCountSeven(countSeven);
            ccor.setCountEight(countEight);
            ccor.setCountNine(countNine);
            ccor.setDealAmount(String.valueOf(dealAmount));
        }
        return rows;
    }


    @Override
    public ChannelCooOrgAgentReportResDto getChannelCooOrgAgentReport(ChannelCooOrgAgentReportReqDto reqDto, PageDTO pageDTO) throws ParseException {
        ChannelCooOrgAgentReportResDto resDto = new ChannelCooOrgAgentReportResDto();
        ChannelReportParam param = new ChannelReportParam();
        param.setPremisesId(reqDto.getPremisesId());
        if(StringUtils.isNotEmpty(reqDto.getBeginDate())){
            param.setBeginDate(DateUtils.stringToDate(reqDto.getBeginDate(), DateStyle.YYYY_MM_DD.getValue()));
        }
        if(StringUtils.isNotEmpty(reqDto.getEndDate())){
            Date endDate = DateUtils.StringToDate(reqDto.getEndDate(), DateStyle.YYYY_MM_DD);
            endDate = DateUtils.addDay(endDate, 1);
            param.setEndDate(endDate);
        }
        param.setAgentCompany(reqDto.getAgentCompany());
        if(Objects.nonNull(reqDto.getDeptId())){
            List<Department> deptList = departmentDao.getChildDeptListByDeptId(reqDto.getDeptId());
            List<Long> deptIds = deptList.stream().map(Department::getId).collect(Collectors.toList());
            param.setDeptIds(deptIds);
        }

        // 未指定分销公司,获取用户所在渠道的所有分销公司
        List<Long> agentCompanies = new ArrayList<>();
        agentCompanies.add(reqDto.getAgentCompany());
        if(Objects.isNull(reqDto.getAgentCompany())){
            PartnerInfo channelPi = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
            agentCompanies = partnerInfoService.listGroupCompanyIdByCompanyId(channelPi.getHigherid(), false);
        }
        if(CollectionUtils.isEmpty(agentCompanies)){
            return resDto;
        }
        param.setAgentCompanies(agentCompanies);

        // 楼盘权限
        List<Long> premisesIds = premisesPermissionService.getPartnerPremisesPermission(Long.valueOf(reqDto.getUserId()));
        if(CollectionUtils.isEmpty(premisesIds)){
            param.setPremisesIds(Arrays.asList(-1L));
        }else{
            param.setPremisesIds(premisesIds);
        }

        // 添加个人权限
        List<Long> agencyDeptIds = deptPermissionService.getPartnerDeptPermission(Long.valueOf(reqDto.getUserId()));
        param.setAgencyDeptIds(agencyDeptIds);

        int count = channelReportDao.getChannelCooOrgAgentReportCount(param);
        List<ChannelCooOrgAgentReport> rows = channelReportDao.getChannelCooOrgAgentReportList(param, (pageDTO.getPageNum() - 1) * pageDTO.getPageSize(), pageDTO.getPageSize());

        Page<ChannelCooOrgAgentReport> page = new Page<>(count, rows);
        page.setPageSize(pageDTO.getPageSize());
        page.setPageNumber(pageDTO.getPageNum());
        resDto.setPageModel(page);
        return resDto;
    }

    @Override
    public CustomerCount getCustomerCount(GetMyCustomerCountReqDto reqDto) {
        PartnerInfo partnerInfo = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
        List<Long> premisesIds = new ArrayList<>();
        CustomerCount resDto = new CustomerCount();
        CustomerCountParam param = new CustomerCountParam();
        param.setPremisesId(reqDto.getCompanyId());
        if(StringUtils.isNotEmpty(reqDto.getStartTime())){
            Date startDate = DateUtils.StringToDate(reqDto.getStartTime(), DateStyle.YYYY_MM_DD);
            param.setStartTime(startDate);
        }
        if(StringUtils.isNotEmpty(reqDto.getEndTime())){
            Date endDate = DateUtils.StringToDate(reqDto.getEndTime(), DateStyle.YYYY_MM_DD);
            endDate = DateUtils.addDay(endDate, 1);
            param.setEndTime(endDate);
        }
        if (reqDto.getCompanyId() != null){
            param.setPremisesId(reqDto.getCompanyId());
        }else{
            // 个人驻守ID
            CaseMemberDto caseMemberDto = new CaseMemberDto();
            caseMemberDto.setPartnerId(partnerInfo.getId());
            caseMemberDto.setCompanyId(partnerInfo.getHigherid());
            List<CaseMember> cmList = caseMemberService.selectListByDto(caseMemberDto);
            premisesIds = cmList.stream().map(CaseMember::getPremisesId).collect(Collectors.toList());

            //当前登录人是否为楼盘项目总监或项目经理
            PremisesDto premisesDto = new PremisesDto();
            premisesDto.setMobileTemp(partnerInfo.getPhone());
            premisesDto.setCompanyId(partnerInfo.getHigherid());
            List<Premises> premisesList = premisesService.selectIdListByMobileTemp(premisesDto);
            if (CollectionUtils.isNotEmpty(premisesList)) {
                for (Premises premises : premisesList) {
                    premisesIds.add(premises.getId());
                }
            }
            param.setPremisesIds(premisesIds);
        }
        // 添加个人权限
        List<Long> agencyDeptIds = deptPermissionService.getPartnerDeptPermissionForWx(Long.valueOf(reqDto.getUserId()));
        param.setAgencyDeptIds(agencyDeptIds);

        //获取报备成功的客户数量
        int successCount = channelReportDao.getCustomerSuccessCount(param);
        int comeToCount = channelReportDao.getCustoemrComeToCount(param);
        resDto.setSuccessCount(successCount);
        resDto.setComeToCount(comeToCount);
        return resDto;
    }





}
